package com.lvtn.adsonandroid;

import java.util.ArrayList;

//import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class NewsActivity extends Activity implements OnItemClickListener{
	private static String AllSaleURL = "http://10.0.2.2/android/getAllSaleAds.php";
	private ProgressDialog pDialog;
	JSONParser jParser = new JSONParser();
	ArrayList<Item> Data;
	JSONArray data_array = null;
	ListView list;
	ListAdapter adapter;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_news);
		Data = new ArrayList<Item>();
		Log.d("asdasdasda","adasdada");
		list = (ListView) findViewById(R.id.listview);
		list.setOnItemClickListener(this);
		// Loading daftar rumah sakit in Background 
		//Thread
		Log.d("asdasdasda","adasdada");
		new GetAllNews().execute();
		// Get listview
		
	}
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Item item = Data.get(position);
		Intent intent = new Intent(NewsActivity.this, DetailSaleActivity.class);
		intent.putExtra("date", item.getPubdate());
		intent.putExtra("user_name", item.getUser());
		intent.putExtra("price", item.getPrice());
		intent.putExtra("title", item.getTitle());
		intent.putExtra("detail", item.getDetail());
		intent.putExtra("news_id", item.getId());
		intent.putExtra("user_email", item.getEmail());
		intent.putExtra("link", item.getLink());
		startActivity(intent);
	}
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
			super.onActivityResult(requestCode, resultCode,	data);
			// if result code 100
			if (resultCode == 100) {
				// if result code 100 is received
				// means user edited/deleted record
				// reload this screen again
				Intent intent = getIntent();
				finish();
				startActivity(intent);
			}
		}
	class GetAllNews extends AsyncTask<String, String, String> {
		
		/**
		* Before starting background thread Show Progress Dialog
		* */
			@Override
			protected void onPreExecute() {
				Log.d("asdasdasda","adasdada");
				super.onPreExecute();
				pDialog = new ProgressDialog(NewsActivity.this);
				pDialog.setMessage("Loading...");
				pDialog.setIndeterminate(false);
				pDialog.setCancelable(false);
				pDialog.show();
			}
		/**
		* getting All record data from url
		* */
			protected String doInBackground(String... args) {
		// Building Parameters
				Log.d("asdasdasda","adasdada");
				List<NameValuePair> params = new ArrayList<NameValuePair>();
		// getting JSON string from URL
				JSONObject json = jParser.makeHttpRequest(AllSaleURL, "GET", params);
		// Check your log cat for JSON reponse
				Log.d("getAllSaleAds: ", json.toString());
				try {
		// Checking for SUCCESS TAG
					int success = json.getInt("success");
					if (success == 1) {
				// Ada record Data (SUCCESS = 1)
				// Getting Array of daftar_rs
						data_array = json.getJSONArray("news");
				// looping through All daftar_rs
						for (int i = 0; i < data_array.length(); i++) {
							JSONObject c = data_array.getJSONObject(i);
					// Storing each json item in variable
							String news_id = c.getString("id");
							String email = c.getString("user_email");
							String title = c.getString("title");
							String price = c.getString("price");
							String detail = c.getString("details");
							String link_image = c.getString("link_image");
							String date = c.getString("created_at");
							String user_name = c.getString("user_name");
							//Log.d("tenuserobj", user_name);
					// creating new HashMap
							Item objItem = new Item();
					// adding each child node to HashMap key => value
							objItem.setTitle(title);
							objItem.setPrice(price);
							objItem.setPubdate(date);
							objItem.setUser(user_name);
						//	Log.d("objsetUser",objItem.setUser(user_name));
							objItem.setLink(link_image);
							objItem.setDetail(detail);
							objItem.setId(news_id);
							objItem.setEmail(email);
					// adding HashList to ArrayList
							Data.add(objItem);
						}
					} else {
				// Tidak Ada Record Data (SUCCESS = 0)
				// Akan menutup aplikasi
			//	Toast toast = Toast.makeText(NewsActivity.this, "Không có tin nào cả", Toast.LENGTH_SHORT);
				//toast.show();
						return null;
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			return null;
			}
		/**
		* After completing background task Dismiss the progress 
		dialog
		* **/
			protected void onPostExecute(String file_url) {
		
				if (null != pDialog && pDialog.isShowing()) {
				pDialog.dismiss();
				}
				if(null == Data || Data.size() == 0){
					Toast toast = Toast.makeText(getApplicationContext(), "Không có tin nào cả", Toast.LENGTH_SHORT);
					toast.show();
				}
				else{
			// updating UI from Background Thread
					
					NewsRowAdapter objAdapter = new NewsRowAdapter(NewsActivity.this,R.layout.item_list, Data);
					list.setAdapter(objAdapter);
				}
			}
		}
		@Override
		public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
			getMenuInflater().inflate(R.menu.news, menu);
			return true;
		}
	
}
